//
//  First_Food_ViewController.swift
//  MyFood
//
//  Created by dllo on 16/2/15.
//  Copyright © 2016年 XRG. All rights reserved.
//

import UIKit
import SwiftyJSON

class First_Food_ViewController: BaseViewController, UICollectionViewDelegate, UICollectionViewDataSource, Recommend_CollectionViewCellDelegate {

    var titlesControl : UISegmentedControl!
    var collectionView : UICollectionView!
    
    var bannerArr : Array<F_LunBo_Model>?
    var wigImageArr : Array<F_Wige_Image_Model>?
    var wigAnotherTwoArr : Array<F_Wige_Image_Model>?
    var todayRecommendArr : Array<F_Wige_Image_Model>?
    var todayRecommendModel : F_widgetList_Model?
    var newYearModel : F_widgetList_Model?
    var congeeModel :  F_widgetList_Model?
    var chooseModel :  F_widgetList_Model?

    override func viewDidLoad() {
        super.viewDidLoad()
        
        createTitleControl()
        createCollectionView()
        createRemmcondData()
        
        // Do any additional setup after loading the view.
    }

    override func viewWillAppear(animated: Bool) {
        self.navigationController?.view.bringSubviewToFront(titlesControl)
        titlesControl.alpha = 1
    }

    override func viewWillDisappear(animated: Bool) {
    self.navigationController?.view.sendSubviewToBack(titlesControl)
        titlesControl.alpha = 0.5
    }

    // 创建标题
    func createTitleControl(){
        titlesControl = UISegmentedControl(items: ["推荐", "食材", "分类"])

        titlesControl.frame = CGRectMake(60, 20, 280, 35)
        self.navigationController?.view.addSubview(titlesControl)
        titlesControl.tintColor = UIColor.clearColor()
        titlesControl.selectedSegmentIndex = 0;
        titlesControl.setTitleTextAttributes([NSFontAttributeName:UIFont.boldSystemFontOfSize(25), NSForegroundColorAttributeName: UIColor.blackColor()], forState: UIControlState.Selected)
        titlesControl.setTitleTextAttributes([NSFontAttributeName: UIFont.boldSystemFontOfSize(25), NSForegroundColorAttributeName: UIColor.grayColor()], forState: UIControlState.Normal)
        titlesControl.selectedSegmentIndex = 0

        titlesControl.addTarget(self, action: "clickSeg:", forControlEvents: UIControlEvents.ValueChanged)

    }

    func clickSeg(seg: UISegmentedControl){
        print(seg.selectedSegmentIndex)
        collectionView.scrollToItemAtIndexPath(NSIndexPath(forRow: seg.selectedSegmentIndex, inSection: 0), atScrollPosition: UICollectionViewScrollPosition.CenteredHorizontally, animated: true)
    }


   func createCollectionView(){

    let flowLayout = UICollectionViewFlowLayout()
    flowLayout.itemSize = CGSizeMake(BASE_WIDTH, BASE_HEIGHT)
    self.collectionView = UICollectionView(frame: CGRectMake(0, 0, BASE_WIDTH, BASE_HEIGHT), collectionViewLayout: flowLayout)
    self.view.addSubview(self.collectionView)
    flowLayout.scrollDirection = UICollectionViewScrollDirection.Horizontal
    flowLayout.minimumInteritemSpacing = 0
    flowLayout.minimumLineSpacing = 0
self.collectionView.registerClass(Recommend_CollectionViewCell.self, forCellWithReuseIdentifier: "RecommendCell")
    self.collectionView.registerClass(Material_CollectionViewCell.self, forCellWithReuseIdentifier: "MaterialCell")
    self.collectionView.registerClass(Classify_CollectionViewCell.self, forCellWithReuseIdentifier: "ClassifyCell")
    collectionView.pagingEnabled = true
    collectionView.bounces = false
    self.collectionView.delegate = self
    self.collectionView.dataSource = self

    }

   func createRemmcondData(){

    let body = "methodName=SceneHome&version=4.3.1&"

    XRAFNetworkTool.POSTUrl(BASE_URL, body: body, requestBodyStyle: XRRequestStyle.String, headFile: nil, response: XRResponseStyle.XRJSON, success: { (dataTask, result) -> Void in

        let json = JSON(result)
        // 轮播图数据
        self.bannerArr = Array()
        let bannerArr = json["data"]["banner"].array

        for temp in bannerArr!{

        let dic: Dictionary = temp.dictionaryObject!
        let model = F_LunBo_Model(dic: dic)
        self.bannerArr?.append(model)

        }

        if self.bannerArr != nil {
            self.collectionView.reloadData()
        }

        let widgetListArr = json["data"]["widgetList"].array
        var widgetModelArr = Array<F_widgetList_Model>()

        for temp in widgetListArr!{

            let dic : Dictionary = temp.dictionaryObject!
            let model = F_widgetList_Model(dic: dic)
            widgetModelArr.append(model)
        }

        for widgetModel in widgetModelArr{

            switch widgetModel.widget_id {

            // 猴年大吉数据
            case 32:

                self.wigImageArr = Array()
                for tempDic in widgetModel.widget_data{

                let wigeImageModel = F_Wige_Image_Model(dic: tempDic)
                self.wigImageArr?.append(wigeImageModel)
                }

                break

            case 33:
                // 新年幸运菜&猴年盛宴
                self.wigAnotherTwoArr = Array()
                for tempDic in widgetModel.widget_data{

                    let wigeImageModel = F_Wige_Image_Model(dic: tempDic)
                    self.wigAnotherTwoArr?.append(wigeImageModel)
                }
                print("猴年盛宴\(self.wigAnotherTwoArr?.count))")
                break

            case 34:
                // 今日食谱推荐
                self.todayRecommendModel = widgetModel
                self.todayRecommendArr = Array()
                for tempDic in widgetModel.widget_data{

                    let wigeImageModel = F_Wige_Image_Model(dic: tempDic)
                    self.todayRecommendArr?.append(wigeImageModel)
                }
                print("今日食谱\(self.todayRecommendArr?.count))")
                break

            case 36:
                // 新春年货DIY
                self.newYearModel = widgetModel
                for tempDic in widgetModel.widget_data{

                    let wigeImageModel = F_Wige_Image_Model(dic: tempDic)
                    self.newYearModel!.myWiget_Data.append(wigeImageModel)
                }
                break
            case 35:
                // 春节来碗养生粥
                self.congeeModel = widgetModel
                for tempDic in widgetModel.widget_data{

                    let wigeImageModel = F_Wige_Image_Model(dic: tempDic)
                    self.congeeModel!.myWiget_Data.append(wigeImageModel)
                }
                break
            case 40:
                // 精选
                self.chooseModel = widgetModel
                for tempDic in widgetModel.widget_data{

                    let wigeImageModel = F_Wige_Image_Model(dic: tempDic)
                    self.chooseModel!.myWiget_Data.append(wigeImageModel)
                }
                break

            default:
            break

            }
        }




        }) { (dataTask, error) -> Void in
            print("error: \(error)")
    }


    }

    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 3
    }

    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

        if indexPath.row == 0{
            
        let cell : Recommend_CollectionViewCell? = collectionView.dequeueReusableCellWithReuseIdentifier("RecommendCell", forIndexPath: indexPath) as? Recommend_CollectionViewCell

            cell?.delegate = self

            if self.bannerArr != nil{
                cell?.bannerArr = self.bannerArr
            }
            if self.wigImageArr != nil{
                cell?.wigImageArr = self.wigImageArr
            }
            if self.wigAnotherTwoArr != nil{
                cell?.wigAnotherTwoArr = self.wigAnotherTwoArr
            }
            if self.todayRecommendArr != nil{
                cell?.todayRecommendArr = self.todayRecommendArr
            }
            if self.newYearModel != nil{
                cell?.newYearModel = self.newYearModel
            }
            if self.congeeModel != nil{
                cell?.congeeModel = self.congeeModel
            }
            if self.chooseModel != nil{
                cell?.chooseModel = self.chooseModel
            }


            return cell!

        }else if indexPath.row == 1{

            let cell : Material_CollectionViewCell? = collectionView.dequeueReusableCellWithReuseIdentifier("MaterialCell", forIndexPath: indexPath) as? Material_CollectionViewCell

            return cell!

        }

        let cell : Classify_CollectionViewCell? = collectionView.dequeueReusableCellWithReuseIdentifier("ClassifyCell", forIndexPath: indexPath) as? Classify_CollectionViewCell

        return cell!
    }

    func scrollViewDidEndDecelerating(scrollView: UIScrollView) {

        let num  = Int(scrollView.contentOffset.x / BASE_WIDTH)
        titlesControl.selectedSegmentIndex = num
    }

    func clickSearch() {
        let searchVC = F_Search_ViewController()
        self.navigationController?.pushViewController(searchVC, animated: true)
    }
    /**
     轮播图的点击

     */
    func clickBanner(num: Int) {
        let model = self.bannerArr![num]
       let webViewVC = F_WebView_ViewController()
        webViewVC.webUrl = model.banner_link
        self.navigationController?.pushViewController(webViewVC, animated: true)
    }

    // 猴年大吉4个按钮点击
    func clickFourButton(btnId: Int) {

        if self.wigImageArr != nil {
        let model = self.wigImageArr![btnId]
        if btnId == 0{
        let webViewVC = F_WebView_ViewController()
        webViewVC.webUrl = model.link
         self.navigationController?.pushViewController(webViewVC, animated: true)
        }else {
            switch btnId {
            case 2:
        let foodVC =  F_FoodMatch_VC()
        self.navigationController?.pushViewController(foodVC, animated: true)
                break
            case 4:
                let allScenceVC =  F_AllScence_ViewController()
                self.navigationController?.pushViewController(allScenceVC, animated: true)
                break
            case 6:
                let myBeYouLikeVC =  F_MaybeYouLike_ViewController()
                self.navigationController?.pushViewController(myBeYouLikeVC, animated: true)
                break
            default:
                print("还没有创建跳转页面")
                break
            }
        }
        }
    }

    // 左右两个图片点击
    func clickImgTap(num: Int) {
        var url = ""
        if num == 0{
            url = "http://h5.izhangchu.com/shaked/index.html?app_hideheader=1&app_exitpage=1&app_exitpage=1&from=app&"

        }else{
            url = "http://h5.izhangchu.com/topic/gather.html?app_hideheader=1&app_exitpage=1&category=1&app_exitpage=1&from=app&"
        }
        let webVC = F_WebView_ViewController()
        self.navigationController?.pushViewController(webVC, animated: true)
        webVC.webUrl = url
    }

    // 2-3 标题点击
    // 跳转到场景单个页面--> webView
    func clickNewYearDIYBigTitlt(linkId: String) {
        // 转到Web
        print(linkId)
        let url = "http://h5.izhangchu.com/web/scene/view.html?&scene_id=\(linkId)"
        let webVC = F_WebView_ViewController()
        self.navigationController?.pushViewController(webVC, animated: true)
        webVC.webUrl = url
    }

    // 2-3 的图片点击
    func clickNewYearImg(linkId: String) {
        print(linkId)
        //1.  跳转到页面
        // body: methodName=DishesView&dishes_id=10245&version=4.3.1&]&
        //2.  调到Web
        let url = "http://h5.izhangchu.com/web/dishes_view/index.html?&dishes_id=\(linkId)"
        let webVC = F_WebView_ViewController()
        self.navigationController?.pushViewController(webVC, animated: true)
        webVC.webUrl = url

    }

    // 所有的播放按钮点击
    func clickMovie(moviePath: String) {

        print("点击视频\(moviePath)")
    }

    // 1 -- 今日食谱 -- 标题点击
    //跳转到场景单个页面--> webView
    func clickSecondTitle() {
       // 1. 手铺转到sigleScene
//        let sigleSceneVC = F_SingleScence_ViewController()
//        let arr = self.newYearModel?.title_link.componentsSeparatedByString("#")
//        let linkId = arr![1]
//        sigleSceneVC.sceneID = Int(linkId)
//                // 自己铺也有数据
//         self.navigationController?.pushViewController(sigleSceneVC, animated: true)

        //2. 跳到web
        if self.newYearModel != nil{
        let arr = self.newYearModel?.title_link.componentsSeparatedByString("#")
        let linkId = arr![1]
        let url =  "http://h5.izhangchu.com/web/scene/view.html?&scene_id=\(linkId)"
        let webVC = F_WebView_ViewController()
        self.navigationController?.pushViewController(webVC, animated: true)
        webVC.webUrl = url
        }

    }

    // 1 -- 今日食谱 -- 图片点击
    func clickSecondImage(linkId: String) {
        print(linkId)
        //1.  跳转到页面
        // body: methodName=DishesView&dishes_id=10245&version=4.3.1&]&

        //2.  调到Web
        let url = "http://h5.izhangchu.com/web/dishes_view/index.html?&dishes_id=\(linkId)"
        let webVC = F_WebView_ViewController()
        self.navigationController?.pushViewController(webVC, animated: true)
        webVC.webUrl = url

    }

    // 4 -- 场景菜谱点击
    func clickSceneMoreClick() {
        let allSceneVC = F_AllScence_ViewController()
        self.navigationController?.pushViewController(allSceneVC, animated: true)
    }

    // 5 -- 精选作品点击
    func clickGoodTitle() {
        print("点击精选作品")
    }
    // 5 -- 精选作品 - 图片点击
    func clickGoodImage(linkId: String) {
        print(linkId)
        //1.  跳转到页面
        // body: post_id=31035&methodName=ShequPostview&version=4.3.1&

        //2.  调到Web
        let url = "http://h5.izhangchu.com/web/post/view.html?&post_id=\(linkId)"
        let webVC = F_WebView_ViewController()
        self.navigationController?.pushViewController(webVC, animated: true)
        webVC.webUrl = url


    }
    // 5 -- 精选作品 - 头像点击
    func clickGoodUserHeadImg(linkId: String) {
        print(linkId)

        let userVC = F_User_ViewController()
        self.navigationController?.pushViewController(userVC, animated: true)
        userVC.userId = linkId
    }


    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
